package com.tvpush.manage.core.service.impl;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tvpush.manage.core.dto.ally.FindAllyInfoDTO;
import com.tvpush.manage.core.entity.AllyInfo;
import com.tvpush.manage.core.entity.Template;
import com.tvpush.manage.core.mapper.AllyInfoMapper;
import com.tvpush.manage.core.mapper.TemplateMapper;
import com.tvpush.manage.core.service.AllyInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ouyangzn
 * @since 2019-03-22
 */
@Service
public class AllyInfoServiceImpl extends ServiceImpl<AllyInfoMapper, AllyInfo> implements AllyInfoService {

    @Autowired
    private TemplateMapper templateMapper;

    @Override
    public Page<AllyInfo> list(FindAllyInfoDTO findDTO) {
        EntityWrapper<AllyInfo> wrapper = new EntityWrapper<>();
        if (StringUtils.isNotBlank(findDTO.getAllyId())) {
            wrapper.eq(AllyInfo.ALLY_ID, findDTO.getAllyId());
        }
        if (StringUtils.isNotBlank(findDTO.getAllyName())) {
            wrapper.eq(AllyInfo.ALLY_NAME, findDTO.getAllyName());
        }
        if (StringUtils.isNotBlank(findDTO.getTemplateName())) {
            List<Template> templates = templateMapper.selectList(new EntityWrapper<Template>().like(Template.TEMPLATE_NAME, "%" + findDTO.getTemplateName() + "%"));
            if (!CollectionUtils.isEmpty(templates)) {
                List<Integer> templateIds = templates.stream().map(t -> t.getTemplateId()).collect(Collectors.toList());
                wrapper.in(AllyInfo.TEMPLATE_ID, templateIds);
            } else {
                wrapper.in(AllyInfo.TEMPLATE_ID, Arrays.asList(-1));
            }
        }
        return this.selectPage(new Page<>(findDTO.getPage(), findDTO.getPageSize()), wrapper);
    }

    @Override
    public void add(AllyInfo addDTO) {
        this.insert(addDTO);
    }

    @Override
    public void update(Integer id, AllyInfo updateDTO) {
        updateDTO.setId(id);
        this.updateById(updateDTO);
    }
}
